var debug = false;
var oc = "grapp";//only code
var url = "http://www.qianfuzhang.com/chrome";
var _loginCookie;
if(debug){
	var host = "http://grapp.grapp-web.com/index/";
}else{
	var host = "http://grapp.qianfuzhang.com/index/";
}

chrome.runtime.sendMessage({cmd: "prohibit"}, function(response) {  
	var _loginCookie = response.uid;	
	var account = response.account;
	if(_loginCookie != undefined){
		var url = domainURI(window.location.href);
		var arr = [ 
					"www.alimama.com",
					"login.taobao.com",
					"detail.tmall.com",
					"item.taobao.com",
					"we.taobao.com",
					"idc.admin.tmall.com",
					"shoucang.taobao.com",
					"list.tmall.com", //天猫列表页
					"s.taobao.com",   //淘宝列表页
					"detail.tmall.hk"
				  ]; 		  
		if(url == arr[0]){
			//$("body").html('');
		}else if(url == arr[1]){
			$(".ph-label").html("");
			$("#TPL_username_1").val(response.username);
			$("#TPL_password_1").val(response.password);
			if($(".ph-label").html() == ''){
				//$("#J_StaticForm").submit();
			}
		}else if(url == arr[2] || url == arr[3] || url == arr[9]){  
			var itemId = getQueryString('id');
			if(itemId>0){
				
				/*
				chrome.runtime.sendMessage({
					cmd: "ajax",
					url: 'http://we.taobao.com/action.do?url=["https://item.taobao.com/item.htm?id=525460450419"]&callback=jsonp50&api=primus_feed_item_addItems'
				}, function(data) { 
					alert(data);
				});
				*/
				
				chrome.runtime.sendMessage({
					cmd: "ajax",
					url: host+'gettaoke/?list_time=1&itemid='+itemId
				}, function(data) {  
					var data = eval("("+data+")");
						var taokprice = data['data']['success'][0]['taokprice'];
						var list_time = data['data']['success'][0]['list_time'];
						var is_collect = data['data']['success'][0]['is_collect'];
						var nick = data['data']['success'][0]['nick'];
						var is_blacklist = data['data']['success'][0]['is_blacklist'];
						
						/* 增加样式 */
						$("body").append('<style>body{margin:0; padding:0;}.grapp-fl{float:left;}.grapp-fr{float:right;}.grapp-clear{clear:both;}.grapp-collect-content{ height:150px; overflow-y:auto; margin-bottom:5px;}.grapp-collect-div .grapp-collect-items{ background:#6AD878; width:50px; height:30px; list-style-type:none; float:left; color:#FFF;font-size:13px; line-height:30px; text-align:center; margin:0 5px 5px 0; border:1px #fff solid; cursor:pointer;}.grapp-collect-div h2{ padding:12px 0; text-align:center; font-size: 20px;}.grapp-collect-div .btn{padding: 2px;}.grapp-collect-div .grapp-collect-items-click{border:1px red solid;}</style>');
						
						/* 创建按钮 */
        				/* $("body").append('<div id="grapp-taoke" style="position:fixed; border:1px solid #F00; bottom:50px; padding:15px; font-weight:bold; font-size:24px; z-index:999999999; background:#F00; color:#FFF; border-radius: 0 0.9em 0.9em 0;">淘客佣金:¥'+taokprice+'<br><a id="grapp-collect" style="color:#fff;">收藏店铺</a></div>');*/
						
						$("body").append('<div id="grapp-taoke" style="position:fixed; border:1px solid #F00; bottom:50px; padding:15px; font-weight:bold; font-size:24px; z-index:999999999; background:#F00; color:#FFF; border-radius: 0 0.9em 0.9em 0;">淘客佣金&nbsp;:&nbsp;¥'+taokprice+'</div>');
						
						/* 收藏宝贝 - start */
						
						var style = "";
							style += "<style>";
							style += ".grapp-cg{position:fixed; bottom:190px; padding:5px 90px; font-weight:bold; font-size:12px; z-index:999999999; border-radius: 0 0.9em 0.9em 0; cursor:pointer;}";
							style += ".grapp-cg-collect{ background: #7C19CB;}"; //已收藏
							style += ".grapp-cg-uncollect{ background: #34A6DA;}"; //未收藏
							style += ".grapp-cg-blacklist{ background: #000000;}"; //未收藏
							style += "</style>";
						$("body").append(style);
						
						if( is_blacklist == 1){
						
							//增加HTML
							$("body").append('<div id="grapp-collect-goods" class="grapp-cg grapp-cg-blacklist"><a href="javascript:void(0);" style="color: #FFFFFf;">黑名单店铺</a></div>');
						
						}else if( is_collect == 1 ){
							
							//增加HTML
							$("body").append('<div id="grapp-collect-goods" class="grapp-cg grapp-cg-collect"><a href="javascript:void(0);" style="color: #FFFFFf;">已收藏</a></div>');
							
						}else{
							
							//增加HTML
							$("body").append('<div id="grapp-collect-goods" class="grapp-cg grapp-cg-uncollect"><a href="javascript:void(0);" style="color: #FFFFFf;">收藏宝贝</a></div>');
							
							var goodsClick = true;
							//绑定事件
							$("#grapp-collect-goods").click(function(){
								if(goodsClick){
									goodsClick = false;									
									chrome.runtime.sendMessage({
										cmd: "ajax",
										dataType: "json",
										url: host+'collectgoods/?itemid='+itemId+'&uid='+_loginCookie+'&account='+account, 
									}, function(data) {
											if(data.status == 3){
												alert("请先登录帐号"); 
												goodsClick = true;
											}else if(data.status == 2){
												alert("已收藏过了");
											}else if(data.status == 1){	
												$("#grapp-collect-goods>a").html("已收藏");
												$("#grapp-collect-goods").removeClass("grapp-cg-uncollect").addClass("grapp-cg-collect");
											}else{
												goodsClick = true;
												alert("收藏失败");	
											}
										}
									);
									
								}
							});	
						}
						
						
						
						
						/* 收藏宝贝 - end */
						
						/* 点击收藏 */
						$("#grapp-collect").click(function(){	
						
							collect.init();
							
							if($(".grapp-collect-div").html() == null){
								$(".grapp-collect-div").html("");
								
								var html = "";
									html += '<div class="grapp-collect-div" style="position:fixed; width:300px; height:300px; bottom:154px; border:3px solid #000; z-index:999999999; background:#FFF; padding:5px; border-radius: 0 0.9em 0.9em 0;"><div style="position: relative;">';
									html += '	<h2 class="grapp-clear" style="color:#22B83B;">选择标签</h2>';
									html += '<span class="grapp-collect-close-div" style="position:absolute;top:0px;right:0;">关闭</span>';
									html += '</div><div class="grapp-collect-content">';
									html += '正在加载中..';
									html += '	</div>';
									html += '	<div>';
									html += '		<p style="min-height: 60px;">选择: <font class="collectSelectedTxt">请选择标签</font></p>';
									html += '	<div>';
									html += '		<input class="grapp-fl btn grapp-save" type="button" value="保存">';
									html += '		<input class="grapp-fr btn grapp-add" type="button" value="新增">';
									html += '		<input class="grapp-fr grapp-addcate" type="text" value="">';
									html += '</div></div></div>';
								
								/* 插入记录 */
								$("#grapp-taoke").before(html);
								
								/* 点击保存 */
								$(".grapp-save").click(function(){			
									if(collectChoiceIdArr.length > 0){
										//淘宝规则
										var cidArr = collectChoiceIdArr.slice(',');
										var shopUrl = $(".tb-shop-name a").attr('href');
										var shopName = $(".tb-shop-name a").attr('title');
										
										//天猫规则
										if(shopUrl === undefined || shopName === undefined){
											shopUrl = $(".slogo-shopname").attr('href');
											shopName = $(".slogo-shopname strong").html();
										}
										
										var url = encodeURIComponent(shopUrl);
										var name = encodeURIComponent(shopName);
										chrome.runtime.sendMessage({
											cmd: "ajax",
											dataType: "json",
											url: host+'addcollect/?cid='+cidArr+'&url='+url+'&name='+name,
										}, function(data) { 
												if(data.status == 3){
													alert("请先登录帐号");
												}else if(data.status == 2){
													alert("已收藏过了");
												}else if(data.status == 1){	
													$("#grapp-collect-goods>a").html("已收藏");
													$("#grapp-collect-goods").removeClass("grapp-cg-uncollect").addClass("grapp-cg-collect");
												}else{
													goodsClick = true;
													alert("收藏失败");	
												}
											}
										);
									}else{
										alert("请选择标签");	
									}
								});
								
								/* 点击新增按钮 */
								$(".grapp-add").click(function(){
									collect.addCate();	
								});	
								
								/* 关闭DIV */
								$(".grapp-collect-close-div").click(function(){
									$('.grapp-collect-div').hide();	
								});
							
							}else{
								$(".grapp-collect-div").show();		
							}
							collect.getCate();
							
						});
						
				});	
				
			}
		}else if(url == arr[4]){
			
			//$(".main-nav").hide();
			
			var adrules = "";
			var adrules_function = {
				
				/* 提示错误(内页专用) */
				show:function(text){
					var arr = [];
					var res = "";
					for(v in adrules){
						res = text.indexOf(adrules[v].adval);
						if(res>-1){
							arr.push(adrules[v].adval);
						}
					}
					return arr;
				},
				
				/* 提醒警告(列表专用) */
				warning:function(text){
					var res = "";
					for(v in adrules){
						res = text.indexOf(adrules[v].adval);
						if(res>-1){
							console.log(adrules[v].adval);
							return true;
						}
					}
					return false;
				}
			};
			
			//默认规则
			chrome.runtime.sendMessage({
				cmd: "ajax",
				dataType : "json",
				url: host+'get_adrules'
			}, function(data){
				adrules = data;
				
				$(".td-contrl").each(function(index){ 
					var _this = this;
					var itemId = $(this).attr('data-id');
					var prevObj = $(this).prev().prev().prev();
					var prevObjVal = $(prevObj).html();
					if(prevObjVal=="单品"){
						
						//默认规则
						/*
						chrome.runtime.sendMessage({
							cmd: "ajax",
							async : false,
							url: host+'getuztaoke/?detail='+itemId
						}, function(data){
							var data = eval("("+data+")");
							if(data['success']==false){
								$(_this).prev().prev().prev().prev().append("<div style='font-size: 14px;color: red;text-align: left;font-weight: bold;'>（"+data['msg']+"）</div>");
							}else{
								var taokprice = data['data']['success'][0]['taokprice'];
								var shopname = data['data']['success'][0]['shopname'];
								var itemId = data['data']['success'][0]['itemId'];
								var nick = data['data']['success'][0]['nick'];
								$(_this).prev().prev().prev().prev().append("<div style='font-size: 14px;color:#750075;text-align: left;font-weight: bold;'>（淘客佣金:¥"+taokprice+"）</div><div style='font-size: 14px;color:#000;text-align: left;font-weight: bold;'>店铺:"+nick+"</div>");
								var html = $(prevObj).html();
								$(prevObj).html('<a href="http://item.taobao.com/item.htm?id='+itemId+'" target="_blank">'+html+"</a>");
							}
						});
						*/
						
						/* 
						*  匹配词库
						*  --开始--
						*/
						$.ajax({
							 timeout : 5000, //超时时间设置，单位毫秒
							 type: 'get',
							 url: "http://we.taobao.com/daren/itemPublish.htm?id="+itemId ,
							 success: function(data){
								 
								 var regExp = /placeholder="请把宝贝链接复制至此，然后单击获取宝贝详情" value="\/\/item.taobao.com\/item.htm\?id=(.*)"/ig;
								 var itemsUrl = data.match(regExp);
									 itemsId = RegExp.$1;
									 if(itemsId>0){ // 如果获取到数据则进行操作
										 chrome.runtime.sendMessage({
											cmd: "ajax",
											async : false,
											url: host+'gettaoke/?isshowshopname=1&itemid='+itemsId
										}, function(data){
											var data = eval("("+data+")");
											if(data['success']==false){
												$(_this).prev().prev().prev().prev().append("<div style='font-size: 14px;color: red;text-align: left;font-weight: bold;'>（"+data['msg']+"）</div>");
											}else{
												var taokprice = data['data']['success'][0]['taokprice'];
												var shopname = data['data']['success'][0]['shopname'];
												var itemId = data['data']['success'][0]['itemId'];
												var nick = data['data']['success'][0]['nick'];
												var auctionId = data['data']['success'][0]['auctionId'];
												var shopTitle = data['data']['success'][0]['shopTitle'];
												$(_this).prev().prev().prev().prev().append("<div style='font-size: 14px;color:#750075;text-align: left;font-weight: bold;'>（淘客佣金:¥"+taokprice+"）</div><div style='font-size: 14px;color:#000;text-align: left;font-weight: bold;'>店铺名称:"+shopTitle+"</div>");
												var html = $(prevObj).html();
												$(prevObj).html('<a href="http://item.taobao.com/item.htm?id='+auctionId+'" target="_blank">'+html+"</a>");
											}
										});
									 }
								 
								 var regExp = /name="title-input" value="(.*)" type/ig;
								 var title = data.match(regExp);
									 title = RegExp.$1;
									 
								 var title_warning = adrules_function.warning(title);
									 if(title_warning){
										$(_this).append("<p style='color:red;'>标题有不符合规则</p>"); 
										return;
									 }
								 var regExp = /推荐理由">(.*)<\//ig;
								 var textarea = data.match(regExp);
									 textarea = RegExp.$1;
									 //console.log(textarea);	
								 
								 var textarea_warning = adrules_function.warning(textarea);	 
									 if(textarea_warning){
										$(_this).append("<p style='color:red;'>内容有不符合规则</p>"); 
										return;
									 }else{
										 $(_this).append("<p style='color:green;'>内容合格</p>"); 
									 }
							 },
							 error: function(){
								$(_this).append("<p style='color:red;'>获取失败</p>"); 
								return;	 
							 },
							 complete : function(XMLHttpRequest,status){ //请求完成后最终执行参数
							　　　　if(status=='timeout'){//超时,status还有success,error等值的情况
							　　　　　  $(_this).append("<p style='color:red;'>超时</p>"); 
							　　　　}
							 }
						});
						/* end */
					}
				});
				
				/* 内页 */
				if($("#J_TitleInput").val().length>0){
					var title = $("#J_TitleInput").val();
					var title_warning = adrules_function.show(title);
					if(title_warning.length > 0){
						$("#J_TitleInput").after("<p style='padding:5px;'>提醒 : 存在违规广告词 \" <span style='color:red; font-size:20px;'>"+title_warning.join()+"</span> \" </p>");
					}else{
						$("#J_TitleInput").after("<p style='padding:5px;'>提醒 : <span style='color:green; font-size:20px;'>合格</span></p>");		
					}
				}
				
				if($(".J_Reason").text().length>0){
					var text = $(".J_Reason").text();
					var arr = adrules_function.show(text);
					if(arr.length > 0){
						$(".J_Reason").after("<p style='padding:5px;'>提醒 : 存在违规广告词 \" <span style='color:red; font-size:20px;'>"+arr.join()+"</span> \" </p>");
					}else{
						$(".J_Reason").after("<p style='padding:5px;'>提醒 : <span style='color:green; font-size:20px;'>合格</span></p>");		
					}
				}
				
			});
			
			
		/* 天猫 */	
		}else if(url == arr[5]){
			/* 控制列表 */
			var idArr = [];
			$(".span4").removeClass('span4').addClass("span6");
			$("table tr").each(function(index){ 
				var _this = $(this).children('td').get(0);
				var _td_a = $(_this).children('a');
				var val = $(_td_a).html();
					val = $.trim(val);
				if(val == "")return;					
				$.ajax({ 
						url: host+'gettaoke/?isshowshopname=1&totalquantity=1&itemid='+val, 
						success: function(data){
							var data = eval("("+data+")");
							if(data['success']==false){
								$(_this).append("<div style='font-size: 12px;color: red;text-align: left;font-weight: bold;'>（"+data['msg']+"）</div>");
							}else{
								var taokprice = data['data']['success'][0]['taokprice'];
								var itemPrice = data['data']['success'][0]['itemPrice'];
								var nick = data['data']['success'][0]['nick'];
								var shopnamenc = hex_md5(nick);
								var itemId = data['data']['success'][0]['itemId'];
								var totalquantity = data['data']['success'][0]['totalquantity'];
								$(_this).append("<div style='font-size: 14px;color:red;text-align: left;font-weight: bold;'><font color='#A1BA2E'>[价格:¥"+itemPrice+"]</font><br>[佣金:¥"+taokprice+"]</div>");
								$(_this).append(
										"<div style='font-size: 13px;color:#000;text-align: left;font-weight: bold;' class='"+shopnamenc+"'>店铺:"+nick+"</div>");
								
								$(_this).append("<div style='font-size: 13px;color:#1FA883;text-align: left;font-weight: bold;''>库存数量:"+totalquantity+"</div>");
								
								//判断数组是否存在
								if(!in_array(shopnamenc,idArr)){
									idArr.push(shopnamenc);
								}else{
									$("."+shopnamenc).css("color","#89F2FF")
								}
							}
							
						},
						error: function(XMLHttpRequest, textStatus, errorThrown) {
							$(_this).prev().append("<div style='font-size: 14px;color: green;text-align: left;font-weight: bold;'>（通信失败）</div>");
						}	
				});
			});	
			
			/* 非法广告词 */
			var adrules = "";
			var adrules_function = {
				
				/* 提示错误（内页专用） */
				show:function(text){
					var arr = [];
					var res = "";
					for(v in adrules){
						res = text.indexOf(adrules[v].adval);
						if(res>-1){
							arr.push(adrules[v].adval);
						}
					}
					return arr;
				},
				
				/* 提醒警告（列表专用） */
				warning:function(text){
					var res = "";
					for(v in adrules){
						res = text.indexOf(adrules[v].adval);
						if(res>-1){
							console.log(adrules[v].adval);
							return true;
						}
					}
					return false;
				}
			};
			
			var pathname = window.location.pathname;
			if(pathname == "/supplierTopicManage.htm"){//判断是否在内页
			
				var GET = $.urlGet();
				if(GET['businessName'] == "tmallchaoliujie"){
			
					//默认规则
					chrome.runtime.sendMessage({
						cmd: "ajax",
						dataType : "json",
						url: host+'get_adrules'
					}, function(data){
						adrules = data;
						$("table>tbody>tr").each(function(index){
							var _this = $(this).find('td').get(0);
							var tr_id = $(this).attr("id");
							/* 
							*  匹配词库
							*  --开始--
							*/
							$.ajax({
								 timeout : 5000, //超时时间设置，单位毫秒
								 type: 'get',
								 url: "http://idc.admin.tmall.com/formInput.htm?id="+tr_id+"&businessName=tmallchaoliujie" ,
								 success: function(data){
									 //console.log(data);
									 var regExp = /values = \{(.+?)};/ig;
									 var title = data.match(regExp);
										 title = title[0];
										 console.log( typeof(title) );
										 title = title.replace("values = ", "");
										 title = title.replace(";", "");
										 console.log( title );
										 //title = "{"+RegExp.$1+"}";
										 var dataObj=eval("("+title+")");
										 if(dataObj){
											 formTitle = dataObj['formTitle'];
											 introForPad = dataObj['introForPad'];
											 var formTitlewarning = adrules_function.warning(formTitle);
											 var introForPadwarning = adrules_function.warning(introForPad);
											 if(formTitlewarning.length > 0 || introForPadwarning.length > 0){
												$(_this).append("<p style='color:red;'>内容有不符合规则</p>"); 
												return;
											 } 
											 var text = "";
											 var items = dataObj['items'];
											 for(val in items){
												textWarning = adrules_function.warning(items[val]['recommend']); 
												if(textWarning){
													$(_this).append("<p style='color:red;'>插件提醒 :内容有不符合规则</p>"); 
													return;
												}
											 }
											 $(_this).append("<p style='color:green;'>插件提醒 :内容合格</p>"); 
										 }else{
											 $(_this).append("<p style='color:red;'>插件提醒 :获取失败</p>"); 
										 }
								 },
								 error: function(){
									$(_this).append("<p style='color:red;'>插件提醒 :获取失败</p>"); 
									return;
								 },
								 complete : function(XMLHttpRequest,status){ //请求完成后最终执行参数
								　　　　if(status=='timeout'){//超时,status还有success,error等值的情况
								　　　　　  $(_this).append("<p style='color:red;'>插件提醒 :超时</p>"); 
								　　　　}
								 }
							});
							/* end */
							return;
							
						});
					});
				}else if(GET['businessName'] == "lifeFamilyAlbum"){ //生活家
					//默认规则
					chrome.runtime.sendMessage({
						cmd: "ajax",
						dataType : "json",
						url: host+'get_adrules'
					}, function(data){
						adrules = data;
						$("table>tbody>tr").each(function(index){
							var _this = $(this).find('td').get(0);
							var tr_id = $(this).attr("id");
							/* 
							*  匹配词库
							*  --开始--
							*/
							$.ajax({
								 timeout : 5000, //超时时间设置，单位毫秒
								 type: 'get',
								 url: "http://idc.admin.tmall.com/formInput.htm?id="+tr_id+"&businessName=tmallchaoliujie" ,
								 success: function(data){
									 //console.log(data);
									 var regExp = /values = \{(.+?)};/ig;
									 var title = data.match(regExp);
										 title = title[0];
										 title = title.replace("values = ", "");
										 title = title.replace(";", "");
										 var dataObj=eval("("+title+")");
										 if(dataObj){
											 albumContent = dataObj['albumContent'];
											 albumDesc = dataObj['albumDesc'];
											 albumTitle = dataObj['albumTitle'];
											 formTitle = dataObj['formTitle'];
											 var albumContentWarning = adrules_function.warning(albumContent);
											 var albumDescWarning = adrules_function.warning(albumDesc);
											 var albumTitleWarning = adrules_function.warning(albumTitle);
											 var formTitleWarning = adrules_function.warning(formTitle);
											 
											 if(albumContentWarning.length > 0 || albumDescWarning.length > 0 || albumTitleWarning.length > 0 || formTitleWarning.length > 0){
												$(_this).append("<p style='color:red;'>内容有不符合规则</p>"); 
												return;
											 } 
											 var text = "";
											 var items = dataObj['items'];
											 for(val in items){
												textWarning = adrules_function.warning(items[val]['recommend']); 
												if(textWarning){
													$(_this).append("<p style='color:red;'>插件提醒 :内容有不符合规则</p>"); 
													return;
												}
												title = adrules_function.warning(items[val]['title']); 
												if(title){
													$(_this).append("<p style='color:red;'>插件提醒 :内容有不符合规则</p>"); 
													return;
												}
											 }
											 $(_this).append("<p style='color:green;'>插件提醒 :内容合格</p>"); 
										 }else{
											 $(_this).append("<p style='color:red;'>插件提醒 :获取失败</p>"); 
										 }
								 },
								 error: function(){
									$(_this).append("<p style='color:red;'>插件提醒 :获取失败</p>"); 
									return;
								 },
								 complete : function(XMLHttpRequest,status){ //请求完成后最终执行参数
								　　　　if(status=='timeout'){//超时,status还有success,error等值的情况
								　　　　　  $(_this).append("<p style='color:red;'>插件提醒 :超时</p>"); 
								　　　　}
								 }
							});
							/* end */
							return;
							
						});
					});
				}
			}
			
			/* 控制内页 */
			if(window.location.pathname == "/formInput.htm"){//判断是否在内页
				
				//默认规则
				chrome.runtime.sendMessage({
					cmd: "ajax",
					dataType : "json",
					url: host+'get_adrules'
				}, function(data){
					adrules = data;
					$(".formgen_text").each(function(index){
						var val = $(this).val();
						var title_warning = adrules_function.show(val);//状态	 
						if(title_warning.length > 0){
							$(this).after("<p style='padding:5px;'>插件提醒 : 存在违规广告词 \" <span style='color:red; font-size:20px;'>"+title_warning.join()+"</span> \" </p>");
						}else{
							$(this).after("<p style='padding:5px;'>插件提醒 : <span style='color:green; font-size:20px;'>合格</span></p>");		
						}
					});
					
					/* 生活家专用 */
					$(".formgen_textarea").each(function(index){
						var val = $(this).val();
						var title_warning = adrules_function.show(val);//状态	 
						if(title_warning.length > 0){
							$(this).after("<p style='padding:5px;'>插件提醒 : 存在违规广告词 \" <span style='color:red; font-size:20px;'>"+title_warning.join()+"</span> \" </p>");
						}else{
							$(this).after("<p style='padding:5px;'>插件提醒 : <span style='color:green; font-size:20px;'>合格</span></p>");		
						}
					});
				});
			}
			
			/*
			 *	搭配
			 */
			if(pathname == "/dapeiManage.htm"){
				//默认规则
				chrome.runtime.sendMessage({
					cmd: "ajax",
					dataType : "json",
					url: host+'get_adrules'
				}, function(data){
					adrules = data;
					console.log( $("table>tbody>tr") );
					$("table>tbody>tr").each(function(index){
						var _this = $(this).find('td').get(0);
						var tr_id = $(this).attr("id");
						$.ajax({
							 timeout : 5000, //超时时间设置，单位毫秒
							 type: 'get',
							 url: "http://idc.admin.tmall.com/formInput.htm?id="+tr_id+"&businessName=tmallchaoliujie" ,
							 success: function(data){
								 $.ajax({
									 timeout : 5000, //超时时间设置，单位毫秒
									 type: 'get',
									 url: "http://idc.admin.tmall.com/dapei.htm?id="+tr_id+"&businessName=tmalldapei" ,
									 success: function(data){
										var regExp = /inputContent=\'\{(.+?)}\';/ig;
								 		var title = data.match(regExp);
											title = title[0];
											title = title.replace("inputContent='", "");
											title = title.replace("';", "");
											var dataObj=eval("("+title+")");
									 		if(dataObj){
												var title = dataObj['title'];
												var introForTmall = dataObj['introForTmall'];
												var Titlewarning = adrules_function.warning(title);
										 		var IntroForTmallwarning = adrules_function.warning(introForTmall);
												if(Titlewarning.length > 0 || IntroForTmallwarning.length > 0){
													$(_this).append("<p style='color:red;'>内容有不符合规则</p>"); 
													return;
										 		} 
											    var text = "";
												var items = dataObj['topic'];
												for(val in items){
													textWarning = adrules_function.warning(items[val]['recommend']); 
													if(textWarning){
														$(_this).append("<p style='color:red;'>插件提醒 :内容有不符合规则</p>"); 
														return;
													}
												}
												$(_this).append("<p style='color:green;'>插件提醒 :内容合格");
											}
									 }
								 });	 
							 }
						});	 
					});
				});
			}
			
			/* 搭配控制内页 */
			if(window.location.pathname == "/dapei.htm"){//判断是否在内页
				
				//默认规则
				chrome.runtime.sendMessage({
					cmd: "ajax",
					dataType : "json",
					url: host+'get_adrules'
				}, function(data){
					adrules = data;
					setTimeout(function(){
						$(".required").each(function(index){
							var val = $(this).val();
							if(isNaN(val)){//只测试为数字的
								var title_warning = adrules_function.show(val);//状态	 
								if(title_warning.length > 0){
									$(this).after("<p style='padding:5px;'>插件提醒 : 存在违规广告词 \" <span style='color:red; font-size:20px;'>"+title_warning.join()+"</span> \" </p>");
								}else{
									$(this).after("<p style='padding:5px;'>插件提醒 : <span style='color:green; font-size:20px;'>合格</span></p>");		
								}
							}
						});	
					}, 5000);
				});
			}
			
		}else if(url == arr[6]){
			 window.setInterval("shoucang()",3000);
		}else if(url == arr[7]){
			$(".product").css("height","410");
			$(".product").each(function(index){ 
				var _this = this;
				var itemId = $(this).attr('data-id');
				chrome.runtime.sendMessage({
					cmd: "ajax",
					url: host+'gettaoke/?itemid='+itemId+'&totalquantity=1', 
				}, function(data) {  
						var data = eval("("+data+")");
						var taokprice = data['data']['success'][0]['taokprice'];
						var totalquantity = data['data']['success'][0]['totalquantity'];
						if(data['success']==false){
							
						}else{
							$(_this).find(".product-iWrap").append('<p class="productStatus" style="text-align: center; line-height: 35px; height:35px;">淘客佣金 <em style="color:red;">¥'+taokprice+'</em> || 库存数量 <em style="color:red;">'+totalquantity+'</em></p>');	
						}
					}
				);
			});
		}else if(url == arr[8]){
			$(".grid>.items").children().each(function(index){ 
				var _this = this;
				$(this).css("height","390");
				var itemId = $(this).find(".J_ItemPicA").attr('data-nid');		
				chrome.runtime.sendMessage({
					cmd: "ajax",
					url: host+'gettaoke/?itemid='+itemId, 
				}, function(data) {  
						var data = eval("("+data+")");
							var taokprice = data['data']['success'][0]['taokprice'];
							$(_this).append('<div class="row row-4" style="text-align:center;   border-top: 1px solid #ededed; line-height: 28px;">淘客佣金: ¥ <font style="color:red; font-weight:bold;">'+taokprice+'</font></div>');
					}
				);
			});
		}
	}
});

/*
*	针对收藏进行特殊处理
*/
function shoucang(){
	$(".g-i-item:not([class='done']").css('height',255);
	$(".g-i-item:not([class='done']").each(function(index){ 
		var _this = this;
		if(!$(_this).is(".done")){
			$(_this).addClass("done");
			var itemId = $(this).attr('data-id');
			
			chrome.runtime.sendMessage({
					cmd: "ajax",
					url: host+'gettaoke/?list_time=1&itemid='+itemId, 
				}, function(data) {  
						var data = eval("("+data+")");
						var taokprice = data['data']['success'][0]['taokprice'];
						var nick = data['data']['success'][0]['nick'];
						if(data['success']==false){
							
						}else{
							$(_this).find(".other-container").before("<p>淘客佣金: ¥ <font style='color:red; font-weight: bold;'>"+taokprice+"</font></p>");
							$(_this).find(".other-container").before("<p>店名:<font style='color:rgb(121, 142, 250); font-weight: bold;'>"+nick+"</font></p>");	
						}
				}	
			);	
		}
	});	
}


function domainURI(str){
    var durl=/[https|http]:\/\/([^\/]+)\//i;
    domain = str.match(durl);
    return domain[1];
}

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}

function in_array(search,array){
	for(var i in array){
		if(array[i]==search){
			return true;
		}
	}
	return false;
}

/* 标签 */
var collectChoiceIdArr = [];
var collectChoiceArr = [];
var collect = {
	
	/* 初始化 */
	init:function(){
		collectChoiceArr = [];
		collectChoiceIdArr = [];
		$(".collectSelectedTxt").html("请选择标签");
	},
	
	
	/* 检查数组 */
	checkArr:function(status,id,name){
		var str = "";
		if(status == "add"){
			collectChoiceArr.push(name);
			collectChoiceIdArr.push(id);
		}else{
			collectChoiceArr.splice($.inArray(name,collectChoiceArr),1);
			collectChoiceIdArr.splice($.inArray(id,collectChoiceIdArr),1);
		}
		if(collectChoiceArr.length>0){
			for(v in collectChoiceArr){
				str += collectChoiceArr[v]+',';	
			}
		}else{
			str = "请先选择";
		}
		$(".collectSelectedTxt").html(str);
	},
	
	
	/* 获取标签列表 */
	getCate:function(){
		var _this = this;
		$.ajax({ 
			url: host+'getcollectcate',
			dataType: "json",
			success: function(data){
				var html = "";
				for(v in data){
					html += '<div class="grapp-collect-items" data-id="'+data[v]['id']+'" data-name="'+data[v]['name']+'">'+data[v]['name']+'</div>';
				}
				$('.grapp-collect-content').html(html);
				
				/* 点击标签 */
				$('.grapp-collect-content div').click(function(){
					var id = $(this).attr("data-id");
					var name = $(this).attr("data-name");
					$(this).toggleClass('grapp-collect-items-click');
					if($(this).hasClass('grapp-collect-items-click')){
						_this.checkArr('add',id,name);
					}else{
						_this.checkArr('del',id,name);
					}
				});
			}
		});
	},
	
	/* 添加新标签 */
	addCate:function(){
		var name = $(".grapp-addcate").val();
		if(name == ''){
			alert("标签为空");
			return;	
		}
		var _this = this;
		$.ajax({ 
			url: host+'addcollectcate/?name='+encodeURIComponent(name),
			dataType: "json",
			success: function(data){
				_this.getCate();
			}
		});	
	}
}

jQuery.cookie = function(name, value, options) { 
    if (typeof value != 'undefined') { // name and value given, set cookie 
        options = options || {}; 
        if (value === null) { 
            value = ''; 
            options.expires = -1; 
        } 
        var expires = ''; 
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { 
            var date; 
            if (typeof options.expires == 'number') { 
                date = new Date(); 
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); 
            } else { 
                date = options.expires; 
            } 
            expires = '; expires=' + date.toUTCString(); 
        } 
        var path = options.path ? '; path=' + (options.path) : ''; 
        var domain = options.domain ? '; domain=' + (options.domain) : ''; 
        var secure = options.secure ? '; secure' : ''; 
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); 
    } else { 
        var cookieValue = null; 
        if (document.cookie && document.cookie != '') { 
            var cookies = document.cookie.split(';'); 
            for (var i = 0; i < cookies.length; i++) { 
                var cookie = jQuery.trim(cookies[i]); 
                if (cookie.substring(0, name.length + 1) == (name + '=')) { 
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); 
                    break; 
                } 
            } 
        } 
        return cookieValue; 
    } 
};

(function($) {
	$.extend({       
		urlGet:function()
		{
			var aQuery = window.location.href.split("?");  //取得Get参数
			var aGET = new Array();
			if(aQuery.length > 1)
			{
				var aBuf = aQuery[1].split("&");
				for(var i=0, iLoop = aBuf.length; i<iLoop; i++)
				{
					var aTmp = aBuf[i].split("=");  //分离key与Value
					aGET[aTmp[0]] = aTmp[1];
				}
			 }
			 return aGET;
		 }
	})
})(jQuery);